package aiku.numericalcontroloa.Service.FinanceManagement.Impl;

import aiku.numericalcontroloa.Base.Utils.BaseEnum;
import aiku.numericalcontroloa.Base.Utils.HttpStatus;
import aiku.numericalcontroloa.Base.Utils.Result;
import aiku.numericalcontroloa.Mapper.*;
import aiku.numericalcontroloa.Mapper.FinanceManagement.AccountMapper;
import aiku.numericalcontroloa.Mapper.FinanceManagement.IncomeExpenditureDetailMapper;
import aiku.numericalcontroloa.Mapper.MasterControl.MessageNotificationMapper;
import aiku.numericalcontroloa.Mapper.OrderManagement.OrderBillingMapper;
import aiku.numericalcontroloa.Mapper.OrderManagement.OrderCommissionMapper;
import aiku.numericalcontroloa.Mapper.OrderManagement.OrderGoodsMapper;
import aiku.numericalcontroloa.Mapper.OrderManagement.OrderMapper;
import aiku.numericalcontroloa.Model.Dto.DevicesDto;
import aiku.numericalcontroloa.Model.Dto.OrderManagement.OrderBillingDto;
import aiku.numericalcontroloa.Model.Dto.PaymentBillingDto;
import aiku.numericalcontroloa.Model.Dto.PurchasePartDto;
import aiku.numericalcontroloa.Model.Entity.*;
import aiku.numericalcontroloa.Model.Entity.FinanceManagement.Account;
import aiku.numericalcontroloa.Model.Entity.FinanceManagement.IncomeExpenditureDetail;
import aiku.numericalcontroloa.Model.Entity.MasterControl.MessageNotification;
import aiku.numericalcontroloa.Model.Entity.OrderManagement.Order;
import aiku.numericalcontroloa.Model.Entity.OrderManagement.OrderBilling;
import aiku.numericalcontroloa.Model.Entity.OrderManagement.OrderCommission;
import aiku.numericalcontroloa.Model.Entity.OrderManagement.OrderGoods;
import aiku.numericalcontroloa.Model.Vo.DevicesVo;
import aiku.numericalcontroloa.Model.Vo.ExpenseVo;
import aiku.numericalcontroloa.Model.Vo.OrderManagement.OrderBillingVo;
import aiku.numericalcontroloa.Service.FinanceManagement.FinanceService;
import aiku.numericalcontroloa.common.utils.DateUtils;
import aiku.numericalcontroloa.enums.RoleEnum;
import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.Year;
import java.time.YearMonth;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

/**
 * @Author 黄广庭
 * @Date 2024/6/10 21:07
 */
@Service
public class FinanceServiceImpl implements FinanceService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderCommissionMapper orderCommissionMapper;
    @Autowired
    private OrderBillingMapper orderBillingMapper;
    @Autowired
    private AccountMapper accountMapper;
    @Autowired
    private ExpenseMapper expenseMapper;
    @Autowired
    private PurchaseOrdersMapper purchaseOrdersMapper;
    @Autowired
    private PaymentBillingMapper paymentBillingMapper;
    @Autowired
    private SuppliersMapper suppliersMapper;
    @Autowired
    private PurchasePartMapper purchasePartMapper;
    @Autowired
    private DevicesMapper devicesMapper;
    @Autowired
    private IncomeExpenditureDetailMapper detailMapper;
    @Autowired
    private DevicesOutboundMapper devicesOutboundMapper;
    @Autowired
    private OrderGoodsMapper orderGoodsMapper;
    @Autowired
    private MessageNotificationMapper msgNotificationMapper;

    @Override
    public Result getBillingList(OrderBillingDto orderBillingDto) {
        if (orderBillingDto == null) {
            return new Result(HttpStatus.BAD_REQUEST, "参数为空(orderBillingDto is null)");
        }
        if (orderBillingDto.getPageSize() == null || orderBillingDto.getCurrentPage() == null) {
            return new Result(HttpStatus.BAD_REQUEST, "分页参数为空");
        }
        Page<OrderBilling> orderBillingPage = new Page<>(orderBillingDto.getCurrentPage(),
                orderBillingDto.getPageSize());
        // 条件查询
        LambdaQueryWrapper<OrderBilling> orderBillingLQW = new LambdaQueryWrapper<>();
        orderBillingLQW.orderByDesc(OrderBilling::getUpdateTime).eq(OrderBilling::getBillStatus, 1);
        if (orderBillingDto.getUserId() != null && !orderBillingDto.getUserId().isEmpty()) {
            // 根据业务员提成id查询
            List<String> orderCommissionIdList = orderCommissionMapper
                    .selectByUserIdWithDelete(orderBillingDto.getUserId())
                    .stream().map(OrderCommission::getId).collect(Collectors.toList());
            orderBillingLQW.in(OrderBilling::getSalesmanCommissionId, orderCommissionIdList);
        }
        if (orderBillingDto.getAccount() != null && !orderBillingDto.getAccount().isEmpty()) {
            // 根据账户查询
            orderBillingLQW.eq(OrderBilling::getAccount, orderBillingDto.getAccount());
        }
        if (orderBillingDto.getYear() != null) {
            // 根据年
            orderBillingLQW.apply("YEAR(date_received) = {0}", orderBillingDto.getYear());
        }
        if (orderBillingDto.getYearMonth() != null) {
            // 根据月
            orderBillingLQW.apply("DATE_FORMAT(date_received, '%Y-%m') = {0}", orderBillingDto.getYearMonth());
        }
        if (orderBillingDto.getYearMonthDay() != null) {
            // 根据日
            orderBillingLQW.apply("DATE(date_received) = {0}", orderBillingDto.getYearMonthDay());
        }
        List<OrderBilling> orderBillingList = orderBillingMapper.selectPage(orderBillingPage, orderBillingLQW)
                .getRecords();
        List<OrderBilling> orderBillingAllList = orderBillingMapper.selectList(orderBillingLQW);
        List<OrderBillingVo> orderBillingVoList = new ArrayList<>();
        BigDecimal totalAmount = new BigDecimal(0);
        Map<String, Object> map = new HashMap<>();
        if (orderBillingList.size() == 0) {
            map.put("total", orderBillingPage.getTotal());
            map.put("totalAmount", totalAmount);
            map.put("orderBillingVoList", orderBillingVoList);
            return Result.success("查询成功", map);
        }

        // 根据订单id查订单列表
        Set<String> orderIdList = orderBillingList.stream().map(OrderBilling::getOrderId).collect(Collectors.toSet());
        List<Order> orderList = orderMapper.selectBatchIdWithDelete(orderIdList, null);
        Map<String, Order> orderMap = orderList.stream().collect(Collectors.toMap(Order::getId, o -> orderList.stream()
                .filter(order -> order.getId().equals(o.getId()))
                .findFirst()
                .orElse(null)));
        // 查业务员
        // 先获取提成列表
        Set<String> salesmanCommissionIdList = orderBillingList.stream().map(OrderBilling::getSalesmanCommissionId)
                .collect(Collectors.toSet());
        List<OrderCommission> salesmanCommissionList = orderCommissionMapper
                .selectBatchIdsWithDelete(salesmanCommissionIdList);
        Map<String, OrderCommission> orderCommissionMap = salesmanCommissionList.stream()
                .collect(Collectors.toMap(OrderCommission::getId, o -> salesmanCommissionList.stream()
                        .filter(commission -> commission.getId().equals(o.getId()))
                        .findFirst()
                        .orElse(null)));
        Set<String> userIdList = salesmanCommissionList.stream().map(OrderCommission::getUserId)
                .collect(Collectors.toSet());
        List<User> userList = userMapper.selectBatchByIdWithDelete(userIdList);
        Map<String, User> userMap = userList.stream().collect(Collectors.toMap(User::getId, u -> userList.stream()
                .filter(user -> user.getId().equals(u.getId()))
                .findFirst()
                .orElse(null)));

        // 查账户
        Set<String> accountIdList = orderBillingList.stream().map(OrderBilling::getAccount).collect(Collectors.toSet());
        List<Account> accountList = accountMapper.selectListByIdWithDelete(accountIdList);
        Map<String, Account> accountMap = accountList.stream()
                .collect(Collectors.toMap(Account::getId, a -> accountList.stream()
                        .filter(account -> account.getId().equals(a.getId()))
                        .findFirst()
                        .orElse(null)));

        // 处理数据
        for (OrderBilling orderBilling : orderBillingList) {
            OrderBillingVo orderBillingVo = new OrderBillingVo();
            BeanUtils.copyProperties(orderBilling, orderBillingVo);
            // 订单流水号
            Order order = orderMap.get(orderBilling.getOrderId());
            orderBillingVo.setSn(order.getSn());
            // 查询业务员姓名
            OrderCommission orderCommission = orderCommissionMap.get(orderBilling.getSalesmanCommissionId());
            User user = userMap.get(orderCommission.getUserId());
            orderBillingVo.setNickName(user.getNickName());
            if (orderBilling.getDateReceived() != null) {
                orderBillingVo.setDateReceived(DateUtils.YMDHMSFormat(orderBilling.getDateReceived()));
            }
            // 查询账户
            if (orderBilling.getAccount() != null) {
                Account account = accountMap.get(orderBilling.getAccount());
                orderBillingVo.setAccount(account.getAccount());
                orderBillingVo.setAccountId(account.getId());
            }
            orderBillingVoList.add(orderBillingVo);
        }
        // 计算总金额
        for (OrderBilling orderBilling : orderBillingAllList) {
            totalAmount = totalAmount.add(orderBilling.getFundsReceived());
        }
        map.put("total", orderBillingPage.getTotal());
        map.put("totalAmount", totalAmount);
        map.put("orderBillingVoList", orderBillingVoList);
        return Result.success("查询成功", map);
    }

    @Override
    public Result getPaymentBillingList(PaymentBillingDto paymentBillingDto) {
        if (paymentBillingDto == null) {
            return new Result(HttpStatus.BAD_REQUEST, "参数为空(paymentBillingDto is null)");
        }
        if (paymentBillingDto.getPageSize() == null || paymentBillingDto.getCurrentPage() == null) {
            return new Result(HttpStatus.BAD_REQUEST, "缺少分页参数");
        }
        Page<PaymentBilling> billingPage = new Page<>(paymentBillingDto.getCurrentPage(),
                paymentBillingDto.getPageSize());
        LambdaQueryWrapper<PaymentBilling> paymentBillingLQW = new LambdaQueryWrapper<>();
        paymentBillingLQW.orderByDesc(PaymentBilling::getUpdateTime).eq(PaymentBilling::getBillsStatus, 1);
        // 根据收款方类型
        if (paymentBillingDto.getPayeeType() != null && paymentBillingDto.getPayeeType() == 0) {
            // 根据员工查报销单
            LambdaQueryWrapper<Expense> expenseLQW = new LambdaQueryWrapper<>();
            expenseLQW.orderByDesc(Expense::getCreateTime);
            if (paymentBillingDto.getPayee() != null) {
                expenseLQW.eq(Expense::getUserId, paymentBillingDto.getPayee());
            }
            List<Expense> expenseList = expenseMapper.selectList(expenseLQW);
            List<String> expenseIdList = new ArrayList<>();
            if (expenseList.isEmpty()) {
                expenseIdList.add("");
            } else {
                expenseIdList = expenseList.stream().map(Expense::getId).collect(Collectors.toList());
            }
            paymentBillingLQW.in(PaymentBilling::getOrderId, expenseIdList);
        } else if (paymentBillingDto.getPayeeType() != null && paymentBillingDto.getPayeeType() == 1) {
            // 根据供应商查采购订单
            LambdaQueryWrapper<PurchaseOrders> purchaseOrdersLQW = new LambdaQueryWrapper<>();
            purchaseOrdersLQW.orderByDesc(PurchaseOrders::getCreateTime);
            if (paymentBillingDto.getPayee() != null) {
                purchaseOrdersLQW.eq(PurchaseOrders::getSuppliersId, paymentBillingDto.getPayee());
            }
            List<PurchaseOrders> purchaseOrdersList = purchaseOrdersMapper.selectList(purchaseOrdersLQW);
            List<String> purchaseOrdersIdList = new ArrayList<>();
            if (purchaseOrdersList.isEmpty()) {
                purchaseOrdersIdList.add("");
            } else {
                purchaseOrdersIdList = purchaseOrdersList.stream().map(PurchaseOrders::getId)
                        .collect(Collectors.toList());
            }
            paymentBillingLQW.in(PaymentBilling::getOrderId, purchaseOrdersIdList);
        }
        if (paymentBillingDto.getAccount() != null && !paymentBillingDto.getAccount().isEmpty()) {
            // 根据账户查询
            paymentBillingLQW.eq(PaymentBilling::getAccount, paymentBillingDto.getAccount());
        }
        if (paymentBillingDto.getYear() != null) {
            // 根据年
            paymentBillingLQW.apply("YEAR(payment_date) = {0}", paymentBillingDto.getYear());
        }
        if (paymentBillingDto.getYearMonth() != null) {
            // 根据月
            paymentBillingLQW.apply("DATE_FORMAT(payment_date, '%Y-%m') = {0}", paymentBillingDto.getYearMonth());
        }
        if (paymentBillingDto.getYearMonthDay() != null) {
            // 根据日
            paymentBillingLQW.apply("DATE(payment_date) = {0}", paymentBillingDto.getYearMonthDay());
        }
        List<PaymentBilling> billingList = paymentBillingMapper.selectPage(billingPage, paymentBillingLQW).getRecords();
        List<PaymentBilling> orderBillingAllList = paymentBillingMapper.selectList(paymentBillingLQW);
        BigDecimal totalAmount = new BigDecimal(0);
        Map<String, Object> map = new HashMap<>();
        List<PaymentBillingDto> paymentBillingDtoList = new ArrayList<>();
        if (billingList.isEmpty()) {
            map.put("total", 0);
            map.put("totalAmount", totalAmount);
            map.put("paymentBillingList", paymentBillingDtoList);
            return Result.success("查询成功", map);
        }

        List<String> orderIdList = billingList.stream().map(PaymentBilling::getOrderId).collect(Collectors.toList());
        // 查供应商，先查采购订单，供应商为月结订单
        List<PurchaseOrders> purchaseOrdersList = purchaseOrdersMapper.selectMonthlyStatementWithDelete(orderIdList);
        List<String> suppliersIdList = new ArrayList<>();
        if (purchaseOrdersList.isEmpty()) {
            suppliersIdList.add("");
        } else {
            suppliersIdList = purchaseOrdersList.stream().map(PurchaseOrders::getSuppliersId)
                    .collect(Collectors.toList());
        }
        // 根据采购订单id获取供应商对象
        List<Suppliers> suppliersList = suppliersMapper.selectBatchByIdWithDelete(suppliersIdList);
        Map<String, Suppliers> suppliersMap = new HashMap<>();
        if (suppliersList.size() > 0) {
            suppliersMap = purchaseOrdersList.stream()
                    .collect(Collectors.toMap(PurchaseOrders::getId, p -> suppliersList.stream()
                            .filter(suppliers -> suppliers.getId().equals(p.getSuppliersId()))
                            .findFirst()
                            .orElse(null)));
        }

        // 查员工，先查报销单
        List<Expense> expenseList = expenseMapper.selectBatchByIdWithDelete(orderIdList);
        Set<String> userIdList = new HashSet<>();
        if (expenseList.isEmpty()) {
            userIdList.add("");
        } else {
            userIdList = expenseList.stream().map(Expense::getUserId).collect(Collectors.toSet());
        }
        // 根据报销单id获取申请人对象
        List<User> userList = userMapper.selectBatchByIdWithDelete(userIdList);
        Map<String, User> userMap = new HashMap<>();
        if (userList.size() > 0) {
            userMap = expenseList.stream().collect(Collectors.toMap(Expense::getId, expense -> userList.stream()
                    .filter(user -> user.getId().equals(expense.getUserId()))
                    .findFirst()
                    .orElse(null)));
        }

        // 查账户
        Set<String> accountIdList = billingList.stream().map(PaymentBilling::getAccount).collect(Collectors.toSet());
        List<Account> accountList = accountMapper.selectListByIdWithDelete(accountIdList);
        Map<String, Account> accountMap = accountList.stream()
                .collect(Collectors.toMap(Account::getId, a -> accountList.stream()
                        .filter(account -> account.getId().equals(a.getId()))
                        .findFirst()
                        .orElse(null)));
        for (PaymentBilling paymentBilling : billingList) {
            PaymentBillingDto paymentBillingVo = new PaymentBillingDto();
            BeanUtils.copyProperties(paymentBilling, paymentBillingVo);
            // 收款方
            if (suppliersMap.containsKey(paymentBilling.getOrderId())) {
                Suppliers suppliers = suppliersMap.get(paymentBilling.getOrderId());
                paymentBillingVo.setPayee(suppliers.getSuppliersName());
            } else {
                User user = userMap.get(paymentBilling.getOrderId());
                paymentBillingVo.setPayee(user.getNickName());
            }
            // 账户
            Account account = accountMap.get(paymentBilling.getAccount());
            paymentBillingVo.setAccount(account.getAccount());
            // 实付日期
            if (paymentBilling.getPaymentDate() != null) {
                paymentBillingVo.setPaymentDate(DateUtils.YMDHMSFormat(paymentBilling.getPaymentDate()));
            }
            paymentBillingDtoList.add(paymentBillingVo);
        }
        // 计算总金额
        for (PaymentBilling orderBilling : orderBillingAllList) {
            totalAmount = totalAmount.add(orderBilling.getPaymentAmount());
        }
        map.put("total", billingPage.getTotal());
        map.put("totalAmount", totalAmount);
        map.put("paymentBillingList", paymentBillingDtoList);
        return Result.success("查询成功", map);
    }

    @Override
    public Result getSupplierBilling(PaymentBillingDto paymentBillingDto) {
        if (paymentBillingDto == null || paymentBillingDto.getPayee() == null ||
                paymentBillingDto.getPayee().isEmpty()) {
            return new Result(HttpStatus.BAD_REQUEST, "缺少参数");
        }
        if (paymentBillingDto.getPageSize() == null ||
                paymentBillingDto.getCurrentPage() == null) {
            return new Result(HttpStatus.BAD_REQUEST, "缺少参数");
        }
        // 查供应商
        Suppliers suppliers = suppliersMapper.selectById(paymentBillingDto.getPayee());
        if (suppliers == null) {
            return new Result(HttpStatus.BAD_REQUEST, "该供应商不存在");
        }
        // 根据供应商查采购账单
        LambdaQueryWrapper<PurchaseOrders> purchaseOrdersLQW = new LambdaQueryWrapper<>();
        purchaseOrdersLQW.eq(PurchaseOrders::getSuppliersId, paymentBillingDto.getPayee());
        if (paymentBillingDto.getPaymentMethod() != null && paymentBillingDto.getPaymentMethod() == 1) {
            // 查月结采购订单
            purchaseOrdersLQW.eq(PurchaseOrders::getPaymentMethod, 1);
        }
        List<PurchaseOrders> purchaseOrdersList = purchaseOrdersMapper.selectList(purchaseOrdersLQW);
        List<String> purchaseOrdersIdList = new ArrayList<>();
        Map<String, PurchaseOrders> purchaseOrdersMap = new HashMap<>();
        if (purchaseOrdersList.isEmpty()) {
            purchaseOrdersIdList.add("");
        } else {
            purchaseOrdersIdList = purchaseOrdersList.stream().map(PurchaseOrders::getId).collect(Collectors.toList());
            purchaseOrdersMap = purchaseOrdersList.stream()
                    .collect(Collectors.toMap(PurchaseOrders::getId, p -> purchaseOrdersList.stream()
                            .filter(purchaseOrders -> purchaseOrders.getId().equals(p.getId()))
                            .findFirst()
                            .orElse(null)));
        }

        Page<PaymentBilling> billingPage = new Page<>(paymentBillingDto.getCurrentPage(),
                paymentBillingDto.getPageSize());
        LambdaQueryWrapper<PaymentBilling> paymentBillingLQW = new LambdaQueryWrapper<>();
        paymentBillingLQW.orderByDesc(PaymentBilling::getCreateTime)
                .in(PaymentBilling::getOrderId, purchaseOrdersIdList);
        // 查月结账单
        // if (paymentBillingDto.getPaymentMethod() != null &&
        // paymentBillingDto.getPaymentMethod() == 1) {
        // paymentBillingLQW.ne(PaymentBilling::getBillsStatus, 1);
        // YearMonth yearMonth = YearMonth.now();
        // paymentBillingLQW.apply("DATE_FORMAT(date_payable, '%Y-%m') = {0}",
        // yearMonth);
        // } else if (paymentBillingDto.getPaymentMethod() == null &&
        // paymentBillingDto.getYearMonth() != null) {
        // // 根据月查询账单
        // paymentBillingLQW.apply("DATE_FORMAT(date_payable, '%Y-%m') = {0}",
        // paymentBillingDto.getYearMonth());
        // }
        // 根据账单状态
        if (paymentBillingDto.getBillsStatus() != null) {
            paymentBillingLQW.eq(PaymentBilling::getBillsStatus, paymentBillingDto.getBillsStatus());
        }

        // List<PaymentBilling> billingList =
        // paymentBillingMapper.selectPage(billingPage, paymentBillingLQW).getRecords();
        List<PaymentBilling> billingList = paymentBillingMapper.selectList(paymentBillingLQW);

        Map<String, Object> map = new HashMap<>();
        List<PaymentBillingDto> paymentBillingDtoList = new ArrayList<>();
        if (billingList.isEmpty()) {
            map.put("total", 0);
            map.put("paymentBillingList", paymentBillingDtoList);
            return Result.success("查询成功", map);
        }

        // 根据采购单查采购人
        Set<String> userIdList = purchaseOrdersList.stream().map(PurchaseOrders::getUserId).collect(Collectors.toSet());
        List<User> userList = userMapper.selectBatchIds(userIdList);
        Map<String, User> userMap = userList.stream().collect(Collectors.toMap(User::getId, u -> userList.stream()
                .filter(user -> user.getId().equals(u.getId()))
                .findFirst()
                .orElse(null)));

        // 查采购零件列表
        LambdaQueryWrapper<PurchasePart> purchasePartLQW = new LambdaQueryWrapper<>();
        purchasePartLQW.in(PurchasePart::getPurchaseId, purchaseOrdersIdList);
        List<PurchasePart> purchasePartList = purchasePartMapper.selectList(purchasePartLQW);
        // 查产品列表
        Set<String> parIdList = purchasePartList.stream().map(PurchasePart::getPartId).collect(Collectors.toSet());
        List<Devices> devicesList = devicesMapper.selectBatchByIdWithDelete(parIdList);
        Map<String, Devices> devicesMap = devicesList.stream()
                .collect(Collectors.toMap(Devices::getId, d -> devicesList.stream()
                        .filter(devices -> devices.getId().equals(d.getId()))
                        .findFirst()
                        .orElse(null)));
        Map<String, List<PurchasePartDto>> purchasePartMap = new HashMap<>();
        for (PurchasePart purchasePart : purchasePartList) {
            Devices devices = devicesMap.get(purchasePart.getPartId());
            PurchasePartDto purchasePartDto = new PurchasePartDto();
            BeanUtils.copyProperties(purchasePart, purchasePartDto);
            purchasePartDto.setPartName(devices.getPartName());
            purchasePartDto.setModel(devices.getModel());
            purchasePartDto.setImage(devices.getImage());
            if (purchasePartMap.containsKey(purchasePart.getPurchaseId())) {
                purchasePartMap.get(purchasePart.getPurchaseId()).add(purchasePartDto);
            } else {
                List<PurchasePartDto> purchasePartDtoList = new ArrayList<>();
                purchasePartDtoList.add(purchasePartDto);
                purchasePartMap.put(purchasePart.getPurchaseId(), purchasePartDtoList);
            }
        }

        // 查账户
        Set<String> accountIdList = billingList.stream().map(PaymentBilling::getAccount).collect(Collectors.toSet());
        List<Account> accountList = accountMapper.selectBatchIds(accountIdList);
        Map<String, Account> accountMap = accountList.stream()
                .collect(Collectors.toMap(Account::getId, a -> accountList.stream()
                        .filter(account -> account.getId().equals(a.getId()))
                        .findFirst()
                        .orElse(null)));
        for (PaymentBilling paymentBilling : billingList) {
            PaymentBillingDto paymentBillingVo = new PaymentBillingDto();
            BeanUtils.copyProperties(paymentBilling, paymentBillingVo);
            // 收款方
            paymentBillingVo.setPayee(suppliers.getSuppliersName());
            // 采购账单
            PurchaseOrders purchaseOrders = purchaseOrdersMap.get(paymentBilling.getOrderId());
            // 采购人
            User user = userMap.get(purchaseOrders.getUserId());
            paymentBillingVo.setUserName(user.getNickName());
            // 零件列表
            paymentBillingVo.setParts(purchasePartMap.get(purchaseOrders.getId()));
            // 总金额
            paymentBillingVo.setPrice(purchaseOrders.getPrice());
            // 下单时间
            paymentBillingVo.setOrderTime(DateUtils.YMDHMSFormat(purchaseOrders.getCreateTime()));
            // 账户
            if (paymentBilling.getAccount() != null) {
                Account account = accountMap.get(paymentBilling.getAccount());
                paymentBillingVo.setAccount(account.getAccount());
            }
            // 实付日期
            if (paymentBilling.getPaymentDate() != null) {
                paymentBillingVo.setPaymentDate(DateUtils.YMDHMSFormat(paymentBilling.getPaymentDate()));
            }
            paymentBillingDtoList.add(paymentBillingVo);
        }

        if (paymentBillingDto.getPaymentMethod() != null && paymentBillingDto.getPaymentMethod() == 1) {
            LocalDate dateEnd = LocalDate.now().with(TemporalAdjusters.lastDayOfMonth());
            LocalDate dateStart = LocalDate.now().with(TemporalAdjusters.firstDayOfMonth());
            paymentBillingDtoList = paymentBillingDtoList.stream().filter(
                    item -> !LocalDate.parse(item.getOrderTime(), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))
                            .isAfter(dateEnd) &&
                            !LocalDate.parse(item.getOrderTime(), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))
                                    .isBefore(dateStart))
                    .collect(Collectors.toList());
        } else if (paymentBillingDto.getPaymentMethod() == null && paymentBillingDto.getYearMonth() != null) {
            LocalDate dateEnd = paymentBillingDto.getYearMonth().atDay(1).plusMonths(1).minusDays(1);
            LocalDate dateStart = paymentBillingDto.getYearMonth().atDay(1);
            paymentBillingDtoList = paymentBillingDtoList.stream().filter(
                    item -> !LocalDate.parse(item.getOrderTime(), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))
                            .isAfter(dateEnd) &&
                            !LocalDate.parse(item.getOrderTime(), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))
                                    .isBefore(dateStart))
                    .collect(Collectors.toList());
        }
        int listLength = paymentBillingDtoList.size();
        int selectPageStart = (int) ((billingPage.getCurrent() - 1) * billingPage.getSize());
        int selectPageEnd = (int) (billingPage.getCurrent() * billingPage.getSize());
        if (selectPageEnd > listLength) {
            selectPageEnd = listLength;
        }
        paymentBillingDtoList = paymentBillingDtoList.subList(selectPageStart, selectPageEnd);
        BigDecimal MtotalAmount = new BigDecimal(0);
        // 计算总金额
        for (PaymentBillingDto orderBilling : paymentBillingDtoList) {
            MtotalAmount = MtotalAmount.add(orderBilling.getPrice());
        }

        // map.put("total", billingPage.getTotal());
        map.put("total", listLength);
        map.put("paymentBillingList", paymentBillingDtoList);
        map.put("MtotalAmount", MtotalAmount);
        return Result.success("查询成功", map);
    }

    public Map<Integer, List<PaymentBillingDto>> getSupplierBillingByIds(List<String> ids) {
        if (ids == null || ids.isEmpty()) {
            throw new RuntimeException("缺少参数");
        }

        // 查供应商
        List<Suppliers> suppliers = suppliersMapper.selectBatchIds(ids);
        if (suppliers == null || suppliers.isEmpty()) {
            throw new RuntimeException("供应商不存在");
        }

        // 根据供应商查采购账单
        LambdaQueryWrapper<PurchaseOrders> purchaseOrdersLQW = new LambdaQueryWrapper<>();
        purchaseOrdersLQW.in(PurchaseOrders::getSuppliersId, ids);
        List<PurchaseOrders> purchaseOrdersList = purchaseOrdersMapper.selectList(purchaseOrdersLQW);
        List<String> purchaseOrdersIdList = new ArrayList<>();
        Map<String, PurchaseOrders> purchaseOrdersMap;
        if (purchaseOrdersList.isEmpty()) {
            purchaseOrdersMap = new HashMap<>();
            purchaseOrdersIdList.add("");
        } else {
            purchaseOrdersIdList = purchaseOrdersList.stream().map(PurchaseOrders::getId).collect(Collectors.toList());
            purchaseOrdersMap = purchaseOrdersList.stream()
                    .collect(Collectors.toMap(PurchaseOrders::getId, p -> purchaseOrdersList.stream()
                            .filter(purchaseOrders -> purchaseOrders.getId().equals(p.getId()))
                            .findFirst()
                            .orElse(null)));
        }

        Page<PaymentBilling> billingPage = new Page<>(1, 10); // 默认第1页,每页10条
        LambdaQueryWrapper<PaymentBilling> paymentBillingLQW = new LambdaQueryWrapper<>();
        paymentBillingLQW.orderByDesc(PaymentBilling::getCreateTime)
                .in(PaymentBilling::getOrderId, purchaseOrdersIdList);

        // 根据账单状态
//         if (paymentBillingDto.getBillsStatus() != null) {
//             paymentBillingLQW.eq(PaymentBilling::getBillsStatus, paymentBillingDto.getBillsStatus());
//         }

        List<PaymentBilling> billingList = paymentBillingMapper.selectList(paymentBillingLQW);

        Map<String, Object> map = new HashMap<>();
        List<PaymentBillingDto> paymentBillingDtoList = new ArrayList<>();
        if (billingList.isEmpty()) {
            map.put("total", 0);
            map.put("paymentBillingList", paymentBillingDtoList);
            return null;
        }

        // 根据采购单查采购人
        Set<String> userIdList = purchaseOrdersList.stream().map(PurchaseOrders::getUserId).collect(Collectors.toSet());
        List<User> userList = userMapper.selectBatchIds(userIdList);
        Map<String, User> userMap = userList.stream().collect(Collectors.toMap(User::getId, u -> userList.stream()
                .filter(user -> user.getId().equals(u.getId()))
                .findFirst()
                .orElse(null)));

        // 查采购零件列表
        LambdaQueryWrapper<PurchasePart> purchasePartLQW = new LambdaQueryWrapper<>();
        purchasePartLQW.in(PurchasePart::getPurchaseId, purchaseOrdersIdList);
        List<PurchasePart> purchasePartList = purchasePartMapper.selectList(purchasePartLQW);
        // 查产品列表
        Set<String> parIdList = purchasePartList.stream().map(PurchasePart::getPartId).collect(Collectors.toSet());
        List<Devices> devicesList = devicesMapper.selectBatchByIdWithDelete(parIdList);
        Map<String, Devices> devicesMap = devicesList.stream()
                .collect(Collectors.toMap(Devices::getId, d -> devicesList.stream()
                        .filter(devices -> devices.getId().equals(d.getId()))
                        .findFirst()
                        .orElse(null)));
        Map<String, List<PurchasePartDto>> purchasePartMap = new HashMap<>();
        for (PurchasePart purchasePart : purchasePartList) {
            Devices devices = devicesMap.get(purchasePart.getPartId());
            PurchasePartDto purchasePartDto = new PurchasePartDto();
            BeanUtils.copyProperties(purchasePart, purchasePartDto);
            purchasePartDto.setPartName(devices.getPartName());
            purchasePartDto.setModel(devices.getModel());
            purchasePartDto.setImage(devices.getImage());
            if (purchasePartMap.containsKey(purchasePart.getPurchaseId())) {
                purchasePartMap.get(purchasePart.getPurchaseId()).add(purchasePartDto);
            } else {
                List<PurchasePartDto> purchasePartDtoList = new ArrayList<>();
                purchasePartDtoList.add(purchasePartDto);
                purchasePartMap.put(purchasePart.getPurchaseId(), purchasePartDtoList);
            }
        }

        // 查账户
        Set<String> accountIdList = billingList.stream().map(PaymentBilling::getAccount).collect(Collectors.toSet());
        List<Account> accountList = accountMapper.selectBatchIds(accountIdList);
        Map<String, Account> accountMap = accountList.stream()
                .collect(Collectors.toMap(Account::getId, a -> accountList.stream()
                        .filter(account -> account.getId().equals(a.getId()))
                        .findFirst()
                        .orElse(null)));
        for (PaymentBilling paymentBilling : billingList) {
            PaymentBillingDto paymentBillingVo = new PaymentBillingDto();
            BeanUtils.copyProperties(paymentBilling, paymentBillingVo);
            // 收款方
            paymentBillingVo.setPayee(suppliers.stream()
                    .filter(s -> s.getId().equals(purchaseOrdersMap.get(paymentBilling.getOrderId()).getSuppliersId()))
                    .findFirst()
                    .orElse(null)
                    .getSuppliersName());
            // 采购账单
            PurchaseOrders purchaseOrders = purchaseOrdersMap.get(paymentBilling.getOrderId());
            // 采购人
            User user = userMap.get(purchaseOrders.getUserId());
            paymentBillingVo.setUserName(user.getNickName());
            // 零件列表
            paymentBillingVo.setParts(purchasePartMap.get(purchaseOrders.getId()));
            // 总金额
            paymentBillingVo.setPrice(purchaseOrders.getPrice());
            // 下单时间
            paymentBillingVo.setOrderTime(DateUtils.YMDHMSFormat(purchaseOrders.getCreateTime()));
            // 账户
            if (paymentBilling.getAccount() != null) {
                Account account = accountMap.get(paymentBilling.getAccount());
                paymentBillingVo.setAccount(account.getAccount());
            }
            // 实付日期
            if (paymentBilling.getPaymentDate() != null) {
                paymentBillingVo.setPaymentDate(DateUtils.YMDHMSFormat(paymentBilling.getPaymentDate()));
            }
            paymentBillingDtoList.add(paymentBillingVo);
        }

        BigDecimal MtotalAmount = new BigDecimal(0);
        // 计算总金额
        for (PaymentBillingDto orderBilling : paymentBillingDtoList) {
            MtotalAmount = MtotalAmount.add(orderBilling.getPrice());
        }

        Map<Integer, List<PaymentBillingDto>> finalMap = paymentBillingDtoList.stream()
                .collect(Collectors.groupingBy(
                        paymentBillingDto -> {
                            String orderTimeStr = paymentBillingDto.getOrderTime();
                            LocalDate orderDate = LocalDate.parse(orderTimeStr, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
                            return orderDate.getMonthValue();
                        }
                ))
                .entrySet()
                .stream()
                .collect(Collectors.toMap(
                        Map.Entry::getKey,
                        Map.Entry::getValue,
                        (oldValue, newValue) -> {
                            List<PaymentBillingDto> mergedList = new ArrayList<>(oldValue);
                            mergedList.addAll(newValue);
                            return mergedList;
                        },
                        () -> IntStream.rangeClosed(1, 12)
                                .boxed()
                                .collect(Collectors.toMap(
                                        Function.identity(),
                                        month -> new ArrayList<>()
                                ))
                ));

//        map.put("total", billingList.size());
//        map.put("paymentBillingList", paymentBillingDtoList);
//        map.put("MtotalAmount", MtotalAmount);
        return finalMap;
    }

    @Override
    @Transactional
    public Result paymentBillingDto(PaymentBillingDto paymentBillingDto) {
        if (paymentBillingDto == null || paymentBillingDto.getIdList().isEmpty()) {
            return new Result(HttpStatus.BAD_REQUEST, "缺少参数");
        }
        if (paymentBillingDto.getAccount() == null) {
            return new Result(HttpStatus.BAD_REQUEST, "缺少参数");
        }
        // 只有管理员和财务有权
        User user = userMapper.selectById(StpUtil.getLoginIdAsString());
        boolean root = user.getRoleId().equals(RoleEnum.ROLE_1.getCodeToString()) ||
                user.getRoleId().equals(RoleEnum.ROLE_6.getCodeToString());
        if (!root) {
            return new Result(HttpStatus.FORBIDDEN, "没有权限");
        }
        Account account = accountMapper.selectById(paymentBillingDto.getAccount());

        // 根据id查账单
        List<PaymentBilling> paymentBillingList = paymentBillingMapper.selectBatchIds(paymentBillingDto.getIdList());
        for (PaymentBilling paymentBilling : paymentBillingList) {
            // 设置账单实付金额
            paymentBilling.setPaymentAmount(paymentBilling.getAmountPayable());
            // 设置账单实付日期
            paymentBilling.setPaymentDate(new Date());
            // 设置账单付款账户
            paymentBilling.setAccount(paymentBillingDto.getAccount());
            // 设置账单状态为已付款
            paymentBilling.setBillsStatus(1);
            // 更新账单
            paymentBillingMapper.updateById(paymentBilling);

            // 新增账户明细
            IncomeExpenditureDetail detail = new IncomeExpenditureDetail();
            // 设置账户id
            detail.setAccountId(account.getId());
            // 设置账单id
            detail.setExpenseId(paymentBilling.getId());
            // 设置明细类型为付款支出
            detail.setDetailType(BaseEnum.ACCOUNT_DETAIL_TYPE_PAYMENT.getCodeInt());
            // 计算余额
            account.setBalance(account.getBalance().subtract(paymentBilling.getPaymentAmount()));
            // 更新账户余额
            LambdaUpdateWrapper<Account> accountLUW = new LambdaUpdateWrapper<>();
            accountLUW.eq(Account::getId, account.getId())
                    .set(Account::getBalance, account.getBalance());
            accountMapper.update(null, accountLUW);
            // 设置余额
            detail.setBalance(account.getBalance());
            // 设置交易时间
            detail.setTradingHours(paymentBilling.getPaymentDate());
            // 设置交易说明
            detail.setTradeComment("月结付款");
            detailMapper.insert(detail);
        }
        return Result.success("操作成功");
    }

    @Override
    public Result getExpenseBilling(PaymentBillingDto paymentBillingDto) {
        if (paymentBillingDto == null ||
                paymentBillingDto.getOrderId() == null || paymentBillingDto.getOrderId().isEmpty()) {
            return new Result(HttpStatus.BAD_REQUEST, "缺少参数");
        }
        LambdaQueryWrapper<PaymentBilling> paymentBillingLQW = new LambdaQueryWrapper<>();
        paymentBillingLQW.eq(PaymentBilling::getOrderId, paymentBillingDto.getOrderId());
        PaymentBilling paymentBilling = paymentBillingMapper.selectOne(paymentBillingLQW);
        if (paymentBilling == null) {
            return new Result(HttpStatus.BAD_REQUEST, "该账单不存在");
        }
        return Result.success("查询成功", paymentBilling);
    }

    @Override
    @Transactional
    public Result paymentExpenseBilling(PaymentBillingDto paymentBillingDto) {
        if (paymentBillingDto == null ||
                paymentBillingDto.getId() == null || paymentBillingDto.getId().isEmpty()) {
            return new Result(HttpStatus.BAD_REQUEST, "缺少参数");
        }
        if (paymentBillingDto.getAccount() == null || paymentBillingDto.getAccount().isEmpty()) {
            return new Result(HttpStatus.BAD_REQUEST, "缺少参数");
        }
        // 查账户
        Account account = accountMapper.selectById(paymentBillingDto.getAccount());
        if (account == null) {
            return new Result(HttpStatus.BAD_REQUEST, "该账户不存在");
        }

        PaymentBilling paymentBilling = paymentBillingMapper.selectById(paymentBillingDto.getId());
        if (paymentBilling == null) {
            return new Result(HttpStatus.BAD_REQUEST, "该账单不存在");
        }

        if (paymentBillingDto.getAmountPayable() != null
                && !paymentBilling.getAmountPayable().equals(paymentBillingDto.getAmountPayable())) {
            LambdaUpdateWrapper<PaymentBilling> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(PaymentBilling::getId, paymentBillingDto.getId()).set(PaymentBilling::getAmountPayable,
                    paymentBillingDto.getAmountPayable());

            LambdaUpdateWrapper<Expense> updateWrapperE = new LambdaUpdateWrapper<>();
            updateWrapperE.eq(Expense::getId, paymentBilling.getOrderId()).set(Expense::getPrice,
                    paymentBillingDto.getAmountPayable());

            if (paymentBillingMapper.update(null, updateWrapper) == 1
                    && expenseMapper.update(null, updateWrapperE) == 1) {
                paymentBilling = paymentBillingMapper.selectById(paymentBillingDto.getId());
            }
        }

        // 实付金额
        paymentBilling.setPaymentAmount(paymentBilling.getAmountPayable());
        // 实付时间
        paymentBilling.setPaymentDate(new Date());
        // 付款账户
        paymentBilling.setAccount(account.getId());
        // 账单状态
        paymentBilling.setBillsStatus(1);
        // 更新账单
        paymentBillingMapper.updateById(paymentBilling);

        // 新增账户明细
        IncomeExpenditureDetail detail = new IncomeExpenditureDetail();
        // 设置账户id
        detail.setAccountId(account.getId());
        // 设置账单id
        detail.setExpenseId(paymentBilling.getId());
        // 设置明细类型为报销支出
        detail.setDetailType(BaseEnum.ACCOUNT_DETAIL_TYPE_REIMBURSEMENT.getCodeInt());
        // 计算余额
        account.setBalance(account.getBalance().subtract(paymentBilling.getPaymentAmount()));
        // 更新账户余额
        LambdaUpdateWrapper<Account> accountLUW = new LambdaUpdateWrapper<>();
        accountLUW.eq(Account::getId, account.getId())
                .set(Account::getBalance, account.getBalance());
        accountMapper.update(null, accountLUW);
        // 设置余额
        detail.setBalance(account.getBalance());
        // 设置交易时间
        detail.setTradingHours(paymentBilling.getPaymentDate());
        // 设置交易说明
        detail.setTradeComment("报销单报销");
        detailMapper.insert(detail);

        // 创建消息通知
        MessageNotification msg = new MessageNotification();
        // 标题
        msg.setTitle("报销单已报销");
        // 内容
        String content = "您的" + paymentBilling.getAmountPayable() + "元报销单已报销";
        msg.setContent(content);
        // 发布人为财务员
        User user = userMapper.selectById(StpUtil.getLoginIdAsString());
        msg.setPublisherId(user.getId());
        // 接收人为申请人
        Expense expense = expenseMapper.selectById(paymentBilling.getOrderId());
        msg.setReceiverId(expense.getUserId());
        // 关联id
        msg.setRelevanceId(expense.getId());
        // 类型为报销管理
        msg.setMsgType(8);
        // 状态为待处理
        msg.setStatus(0);
        msgNotificationMapper.insert(msg);
        return Result.success("操作成功");
    }

    @Override
    public Result calculatingProfit(DevicesDto devicesDto) {
        if (devicesDto == null) {
            return new Result(HttpStatus.BAD_REQUEST, "缺少参数(devicesDto is null)");
        }
        if (devicesDto.getCurrentPage() == null || devicesDto.getPageSize() == null) {
            return new Result(HttpStatus.BAD_REQUEST, "缺少分页参数");
        }
        Page<Devices> devicesPage = new Page<>(devicesDto.getCurrentPage(), devicesDto.getPageSize());

        // 查询产品表
        LambdaQueryWrapper<Devices> devicesLQW = new LambdaQueryWrapper<>();
        devicesLQW.orderByDesc(Devices::getCreateTime);
        if (devicesDto.getIsProduct() != null) {
            devicesLQW.eq(Devices::getIsProduct, devicesDto.getIsProduct());
        }
        if (devicesDto.getWarehouseType() != null) {
            devicesLQW.eq(Devices::getWarehouseType, devicesDto.getWarehouseType());
        }
        if (devicesDto.getPartName() != null) {
            devicesLQW.and(lqw -> lqw.like(Devices::getPartName, devicesDto.getPartName())
                    .or().like(Devices::getModel, devicesDto.getPartName()));
        }

        List<Devices> devicesList = null;
        if (devicesDto.getSelect() != null) {
            devicesList = devicesMapper.selectList(devicesLQW);
        } else {
            devicesList = devicesMapper.selectPage(devicesPage, devicesLQW).getRecords();
        }

        List<DevicesVo> devicesVoList = new ArrayList<>();
        Map<String, Object> map = new HashMap<>();
        if (devicesList.isEmpty()) {
            map.put("total", 0);
            map.put("devicesVoList", devicesVoList);
            return Result.success("查询成功", map);
        }

        // 查询出库表，类型为卖出商品，状态为出库成功，审核时间为出库时间，根据审核时间查本月
        LambdaQueryWrapper<DevicesOutbound> devicesOutboundLQW = new LambdaQueryWrapper<>();
        YearMonth nowMonth = YearMonth.now();
        if (devicesDto.getYearMonth() != null) {
            nowMonth = devicesDto.getYearMonth();
        }
        devicesOutboundLQW.eq(DevicesOutbound::getType, 0)
                .eq(DevicesOutbound::getStatus, 4)
                .apply("DATE_FORMAT(outbound_time, '%Y-%m') = {0}", nowMonth);
        List<DevicesOutbound> devicesOutboundList = devicesOutboundMapper.selectList(devicesOutboundLQW);
        List<String> orderIdList = new ArrayList<>();
        if (devicesOutboundList.isEmpty()) {
            orderIdList.add("");
        } else {
            orderIdList = devicesOutboundList.stream().map(DevicesOutbound::getReturnId).collect(Collectors.toList());
        }
        // 根据订单id集合查询订单产品表
        LambdaQueryWrapper<OrderGoods> orderGoodsLQW = new LambdaQueryWrapper<>();
        orderGoodsLQW.in(OrderGoods::getOrderId, orderIdList);
        List<OrderGoods> orderGoodsList = orderGoodsMapper.selectList(orderGoodsLQW);
        // 将订单产品集合处理成Map<String,List<OrderGoods>>，key为产品id
        Map<String, List<OrderGoods>> orderGoodsMap = new HashMap<>();
        if (orderGoodsList.size() > 0) {
            for (OrderGoods orderGoods : orderGoodsList) {
                if (orderGoodsMap.containsKey(orderGoods.getGoodsId())) {
                    orderGoodsMap.get(orderGoods.getGoodsId()).add(orderGoods);
                } else {
                    List<OrderGoods> goodsList = new ArrayList<>();
                    goodsList.add(orderGoods);
                    orderGoodsMap.put(orderGoods.getGoodsId(), goodsList);
                }
            }
        }
        // 计算利润
        for (Devices devices : devicesList) {
            DevicesVo devicesVo = new DevicesVo();
            BeanUtils.copyProperties(devices, devicesVo);
            // 单个产品毛利润计算：销售单价-成本费或采购单价-运输费
            BigDecimal devicesGrossProfit = (devices.getPrice().subtract(devices.getCost()))
                    .subtract(devices.getFreight());
            // 单个产品净利润计算：销售单价-成本费或采购单价-运输费-其他费用
            // 减去加工费
            BigDecimal process = devicesGrossProfit.subtract(devices.getProcess());
            // 减去人工费
            BigDecimal labour = process.subtract(devices.getLabour());
            // 减去打包费
            BigDecimal packing = labour.subtract(devices.getPacking());
            // 减去场地费
            BigDecimal devicesNetProfit = packing.subtract(devices.getFreight());
            // 月销售数
            float salesQuantity = 0;
            if (orderGoodsMap.containsKey(devices.getId())) {
                for (OrderGoods orderGoods : orderGoodsMap.get(devices.getId())) {
                    salesQuantity = salesQuantity + orderGoods.getGoodsCount();
                }
            }
            // 月毛利润
            BigDecimal grossProfit = devicesGrossProfit.multiply(new BigDecimal(salesQuantity));
            // 月净利润
            BigDecimal netProfit = devicesNetProfit.multiply(new BigDecimal(salesQuantity));
            devicesVo.setSalesQuantity(salesQuantity);
            devicesVo.setGrossProfit(grossProfit);
            devicesVo.setNetProfit(netProfit);
            devicesVoList.add(devicesVo);
        }

        LambdaQueryWrapper<DevicesOutbound> dqw = new LambdaQueryWrapper<>();
        dqw.eq(DevicesOutbound::getType, 0)
                .eq(DevicesOutbound::getStatus, 4)
                .apply("YEAR(outbound_time)=YEAR(NOW())");
        List<String> ol = devicesOutboundMapper.selectList(dqw).stream().map(DevicesOutbound::getReturnId)
                .collect(Collectors.toList());
        LambdaQueryWrapper<OrderGoods> oqw = new LambdaQueryWrapper<>();
        if (!ol.isEmpty()) {
            oqw.in(OrderGoods::getOrderId, ol);
        }
        List<OrderGoods> ogl = orderGoodsMapper.selectList(oqw);
        Map<String, List<OrderGoods>> ogm = new HashMap<>();
        if (ogl.size() > 0) {
            for (OrderGoods orderGoods : ogl) {
                if (ogm.containsKey(orderGoods.getGoodsId())) {
                    ogm.get(orderGoods.getGoodsId()).add(orderGoods);
                } else {
                    List<OrderGoods> goodsList = new ArrayList<>();
                    goodsList.add(orderGoods);
                    ogm.put(orderGoods.getGoodsId(), goodsList);
                }
            }
        }
        devicesVoList.forEach(item -> {
            float salesQuantity = 0;
            if (ogm.containsKey(item.getId())) {
                for (OrderGoods orderGoods : ogm.get(item.getId())) {
                    if (orderGoods.getGoodsCount() != null) {
                        salesQuantity = salesQuantity + orderGoods.getGoodsCount();
                    }
                }
            }
            item.setNsalesQuantity(salesQuantity);
        });

        long listLength;
        if (devicesDto.getSelect() != null) {
            switch (devicesDto.getSelect()) {
                case 1:
                    devicesVoList = devicesVoList.stream()
                            .sorted(Comparator.comparing(DevicesVo::getSalesQuantity).reversed()
                                    .thenComparing(DevicesVo::getNsalesQuantity).reversed())
                            .collect(Collectors.toList());
                    break;
                case 2:
                    devicesVoList = devicesVoList.stream().sorted(Comparator.comparing(DevicesVo::getSalesQuantity)
                            .thenComparing(DevicesVo::getNsalesQuantity).reversed()).collect(Collectors.toList());
                    break;
                case 3:
                    devicesVoList = devicesVoList.stream()
                            .sorted(Comparator.comparing(DevicesVo::getNsalesQuantity).reversed()
                                    .thenComparing(DevicesVo::getSalesQuantity).reversed())
                            .collect(Collectors.toList());
                    break;
                case 4:
                    devicesVoList = devicesVoList.stream().sorted(Comparator.comparing(DevicesVo::getNsalesQuantity)
                            .thenComparing(DevicesVo::getSalesQuantity).reversed()).collect(Collectors.toList());
                    break;
            }
            listLength = devicesVoList.size();
            int selectPageStart = (int) ((devicesPage.getCurrent() - 1) * devicesPage.getSize());
            int selectPageEnd = (int) (devicesPage.getCurrent() * devicesPage.getSize());
            if (selectPageEnd > listLength) {
                selectPageEnd = (int) listLength;
            }
            devicesVoList = devicesVoList.subList(selectPageStart, selectPageEnd);
        } else {
            listLength = devicesPage.getTotal();
        }
        map.put("total", devicesPage.getTotal());
        map.put("devicesVoList", devicesVoList);
        return Result.success("查询成功", map);
    }
}
